package com.gzsxy.esjy.message.handler;

import java.util.Map;

import com.gzsxy.esjy.message.netty.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;



import io.netty.channel.Channel;

/**
 * 消息处理业务
 * @author hezhiyuan
 *
 */
@Service
public class MessageCenterService {

	@Value("${spring.application.name}")
	private String application ;
	
	@SuppressWarnings("rawtypes")
	private final Map<String,IMessageCenterHandler> handlers ;
	
	public MessageCenterService(ApplicationContext context) {
		super();
		this.handlers = context.getBeansOfType(IMessageCenterHandler.class);
	}

	/**
	 * 业务处理
	 * @param message
	 * @param channel
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void service(Message message, Channel channel) {
		String cmd = message.getCmd();
		cmd = cmd.replace(application, "");
		IMessageCenterHandler iMessageCenterHandler = handlers.get(cmd);
		if(iMessageCenterHandler == null) {
			channel.writeAndFlush(Message.warn( cmd+" 不存在")) ;
			return ;
		}
		iMessageCenterHandler.handler(iMessageCenterHandler.convert(message.getBody()), channel);
	}
}
